'''
Created on 12.12.2012

@author: doleynik
'''
import os
import jinja2
from webapp2_extras import i18n

import zipfile
import StringIO
import time

from common import functions
from BaseHandler import BaseHandler
from google.appengine.api import users
from apnetmodels.basicmodels import  immeuble, period_concept, fundraising
#from docx.docx import *
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from operator import itemgetter, attrgetter

def srtLot(a,b):
        if a.isdigit() and b.isdigit():
            return int(a) - int(b)
        elif a.isdigit() and not b.isdigit():
            return 100000
        elif not a.isdigit() and b.isdigit():
            return -100000
        else:
            return cmp(a , b)

class MainReport(BaseHandler):


    def get(self, imm_id, command=None, p_id=None):
        if command == 'list':
            self.op_list(imm_id)
        if command == 'report1' or command == 'budget':
            self.op_budget_previsionel(imm_id, period_id = p_id)
        elif command == 'report2' or command == 'LotsList':
            self.op_LotsList(imm_id)
        elif command == 'report3':
            self.op_Budget(imm_id)
        elif command == 'report4' or command == 'fundraising':
            self.op_AppFond(imm_id, frreq_id = p_id)

            
    def post(self, imm_id, command=None):
        pass

    def draw_header(self,imm,ssyn,c,title,title2=None):
        
        secs = time.clock()
        ttime = time.asctime(time.localtime(secs))
        

        c.setStrokeColorRGB(0.5,0.5,0.5)
        c.setFillColorRGB(0.9,0.9,0.9)
        c.rect(20,-130,250,130, fill=0)
        #c.roundRect(20,-130,200,130, 10, stroke=1, fill=0)
        c.setFillColorRGB(0.1,0.1,0.1)
        DDy = -10.
        deltaY = 12.
        c.setFont("Helvetica", 6)
        c.drawString(30, DDy, unicode("Syndic:" ))
        DDy = DDy - deltaY
        c.setFont("Helvetica", 10)
        c.drawString(40, DDy, unicode(ssyn.name))
        DDy = DDy - deltaY
        addr = ssyn.adress.splitlines()
        for lem in addr:
            c.drawString(40, DDy, unicode(lem))
            DDy = DDy - deltaY
        c.drawString(40, DDy, unicode(ssyn.additional_adress))
        DDy = DDy - deltaY
        c.drawString(40, DDy, unicode(ssyn.postalcode) + unicode(' ') + unicode(ssyn.ville))
        DDy = DDy - deltaY - 20
        c.setFont("Helvetica", 6)
        c.drawString(30, -109,"Phone: "+ unicode(ssyn.phone))
        DDy = DDy - 9
        c.drawString(30, -117,"Fax  : "+ unicode(ssyn.fax))
        DDy = DDy - deltaY
        c.drawString(30, -125,"E-mail : "+ unicode(ssyn.email))
        DDy = -25
        c.setStrokeColorRGB(0.5,0.5,0.5)
        c.setFillColorRGB(0.9,0.9,0.9)
        c.rect(300,-80,270,80, fill=0)
        c.rect(300,-130,270,45, fill=0)
        #c.roundRect(300,-80,270,80, 10, stroke=1, fill=1)
        c.setFillColorRGB(0.0,0.0,0.0)
        c.line(300, -20, 570, -20)

        c.setFont("Helvetica", 10)
        c.drawCentredString(410, -10,unicode(title))
        
        if title2:
            c.setFont("Helvetica", 6) 
            c.drawCentredString(410, -18,unicode(title2))
        DDy = DDy - 6
        c.setFont("Helvetica", 6)
        c.drawString(310, DDy,"Copropriete : ")
        DDy = DDy - deltaY
        c.setFont("Helvetica", 8)
        deltaY = 10
        c.drawString(320, DDy, unicode(imm.name))
        DDy = DDy - deltaY
        c.drawString(320, DDy, unicode(" %s %s" % (imm.pobox, imm.street)))#imm.adress
        DDy = DDy - deltaY
        #c.drawString(340, DDy, unicode(imm.additional_adress.strip()))
        c.drawString(320, DDy, unicode(" %s %s" % (imm.zip, imm.city)))
        #c.drawRightString(570, -139, unicode("le %s" % ttime))

    def op_budget_previsionel(self, imm_id, period_id):# PDF  Budget Prevision)
        
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        period = period_concept.get_by_id(int(period_id))
        periAll = period_concept.all() #.get()
        # part to find previous period 
        periNew = period
        periLast = period
        for ipr in periAll:
            if ipr.date_finish < period.date_start :
                if periLast == period: 
                    periLast = ipr
                elif ipr.date_finish > periLast.date_finish :
                    periLast = ipr
            elif ipr.date_start > period.date_finish :
                if periNew == period :
                    periNew = ipr
                elif ipr.date_start < periNew.date_start:
                    periNew = ipr
        
        imm = period.immeuble
        ssyn = imm.syndic

        breg = period.get_budget('Regular')     #- return regular budget
        badd = period.get_budget('Additional')  #- return additional budget
        
        # part to merge current and previous period in same table
        # including 'charges_key' & 'expenditure'
        #
        self.response.headers['Content-Type'] = 'application/pdf'
        self.response.headers['Content-Disposition'] = 'attachment; filename=BudgetPrevis.pdf'

        c = canvas.Canvas(self.response.out, pagesize=A4)
        pwidth, pheight = A4
        c.translate(0,pheight-50)
        c.saveState() 

        title = "Budget previsionel"
        self.draw_header(imm,ssyn,c,title)
        DDy = -110.
        deltaY = 12.
        c.drawString(320, DDy, unicode("Exercice du %s" % period))
        DDy = -160

        for pnom in ['Regular','Additional']:
            b = period.get_budget(pnom) #- return full budget
            o = b.keys() 
            #
            if periLast != period:
                bl = periLast.get_budget(pnom)
                ol = bl.keys()
                for iil in ol:
                    if iil not in o:
                        o.append(iil)
                        b[iil]['item_list'] = bl[iil]['item_list']
                        for n in b[iil]['item_list']:
                            n['amount_prev'] = n['amount']
                            n['amount'] = 0.0
                    else:
                        for nn in bl[iil]['item_list']:
                            found = False
                            for n in b[iil]['item_list']:
                                if unicode(n['expenditure']) == unicode(nn['expenditure']):
                                    n['amount_prev'] = nn['amount']
                                    found = True
                            if not found:
                                nn['amount_prev'] = nn['amount']
                                nn['amount'] = 0.0
                                b[iil]['item_list'].append(nn)

            if periNew != period:
                bn = periNew.get_budget(pnom)
                on = bn.keys()
                for iil in on:
                    if iil not in o:
                        o.append(iil)
                        b[iil]['item_list'] = bn[iil]['item_list']
                        for n in b[iil]['item_list']:
                            n['amount_new'] = n['amount']
                            n['amount'] = 0.0
                    else:
                        for nn in bn[iil]['item_list']:
                            found = False
                            for n in b[iil]['item_list']:
                                if unicode(n['expenditure']) == unicode(nn['expenditure']):
                                    n['amount_new'] = nn['amount']
                                    found = True
                            if not found:
                                nn['amount_new'] = nn['amount']
                                nn['amount'] = 0.0
                                b[iil]['item_list'].append(nn)

                    o.sort()   # key sorting for output by 'charges_key'

        
            # Draw a table 
            c.setStrokeColorRGB(0.0,0.0,0.0)
            c.setFillColorRGB(0.9,0.9,0.9)
            c.rect(10,DDy-20,560,20, fill=0)
            c.setFont("Helvetica", 8)
            c.setStrokeColorRGB(0.,0.,0.)
            c.setFillColorRGB(0.0,0.0,0.0)
        


            ttl = period.get_sum_by_charges_keys()
        
        
            rrow = [50, 360, 410, 460, 510]#
            lrow = [10, 355, 405, 455, 505,570]
            rnom = ['Intitules', 'Budget N-1',period,'Reel N','Budget N+1']
            c.drawString(40 , DDy+3, unicode("Budget %s" % pnom))
            for qq, qn in map(None,rrow,rnom): # header
                if qq in [410]:
                    c.setFont("Helvetica", 7)
                    c.drawString(qq , DDy-10, unicode(qn.date_start).strip())
                    c.drawString(qq+3 , DDy-18, unicode(qn.date_finish).strip())
                elif qq == 360 and periLast != period:
                    c.setFont("Helvetica", 7)
                    c.drawString(qq , DDy-10, unicode(periLast.date_start).strip())
                    c.drawString(qq+3 , DDy-18, unicode(periLast.date_finish).strip())
                elif qq == 510 and periNew != period:
                    c.setFont("Helvetica", 7)
                    c.drawString(qq , DDy-10, unicode(periNew.date_start).strip())
                    c.drawString(qq+3 , DDy-18, unicode(periNew.date_finish).strip())
                else:
                    c.setFont("Helvetica", 8)
                    c.drawString(qq , DDy-12, unicode(qn).strip())
            
            for lc in lrow: # vertical lines
                c.line(lc,DDy-deltaY-8,lc,DDy)

            deltaY=12
            DDy = DDy - 30 
 

            toto = 0.0
            totoL = 0.0
            totoN = 0.0
            c.setFont("Helvetica", 8)
        
            for i in o:
                c.drawString(20, DDy, unicode(i))
                for lc in lrow:
                    c.line(lc,DDy- deltaY-3,lc,DDy+deltaY)
                DDy = DDy - deltaY 
                totoL_chk = 0
                totoN_chk = 0
                for n in b[i]['item_list']:
                    c.setFont("Helvetica", 7)   
                    c.drawString(40, DDy, unicode(n['expenditure']))
                    c.drawRightString(400, DDy, unicode(n['amount_prev']))         
                    c.drawRightString(450, DDy, unicode(n['amount']))
                    c.drawRightString(560, DDy, unicode(n['amount_new']))         
                    totoL_chk = totoL_chk + n['amount_prev']
                    totoN_chk = totoN_chk + n['amount_new']
                    for lc in lrow:
                        c.line(lc,DDy-deltaY-3,lc,DDy)
                    DDy = DDy - deltaY    
                   
                totoL = totoL + totoL_chk
                totoN = totoN + totoN_chk
                c.setFont("Helvetica", 8)
                c.drawString(20, DDy, unicode("Total de %s" % i))
                c.drawRightString(450, DDy, unicode(ttl[i]['amount']))
                c.drawRightString(400, DDy, unicode(totoL_chk))
                c.drawRightString(560, DDy, unicode(totoN_chk))
                toto = toto + ttl[i]['amount']
            
                c.line(10, DDy-3, 570, DDy-3)
                DDy = DDy - deltaY

            c.drawString(40, DDy, unicode("Total general"))
            c.drawRightString(450, DDy, unicode(toto))
            c.drawRightString(400, DDy, unicode(totoL))
            c.drawRightString(560, DDy, unicode(totoN))

            for lc in lrow:
                c.line(lc,DDy-3,lc,DDy+deltaY)
            c.line(10, DDy-3, 570, DDy-3) 
            DDy = DDy - 2*deltaY   
        
        c.restoreState()
        c.showPage()
        c.save()

              
    def op_LotsList(self, imm_id):# PDF LotsList (after Budget)
        
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        imm = immeuble.get_by_id(int(imm_id))  
        ssyn = imm.syndic
        
        self.response.headers['Content-Type'] = 'application/pdf'
        self.response.headers['Content-Disposition'] = 'attachment; filename=LotsList.pdf'
        
        c = canvas.Canvas(self.response.out, pagesize=A4)
        pwidth, pheight = A4
        c.translate(0,pheight-50)
        c.saveState() 

        title = "Lots List"
        title2 = "et milliemes "
        self.draw_header(imm,ssyn,c,title,title2)

        deltaY = 12.
        DDy = -180
        # Draw a table
        c.setStrokeColorRGB(0.0,0.0,0.0)
        c.setFillColorRGB(0.9,0.9,0.9)
        c.rect(10,DDy-20,560,20, fill=0)
        c.setFont("Helvetica", 8)
        c.setStrokeColorRGB(0.,0.,0.)
        c.setFillColorRGB(0.,0.,0.)
        #c.setFillColorRGB(0,0,0)
        rrow = [20,  80,  170,  210, 250, 283, 335, 445, 532]#
        lrow = [30, 150,  190, 230, 265, 300, 380, 505,570]#
        rnom = ['Lot', 'type', 'batiment', 'escalier', 'etage',
                 'surface', 'Proprietaire','Cle de repartition','Tantieme']
        kk = 0
        for qq, qn in map(None,rrow,rnom): # header
                #sw = c.stringWidth( unicode(qn).strip())/2
                c.line(lrow[kk],DDy-20,lrow[kk],DDy)
                c.drawCentredString(rrow[kk] , DDy-12, unicode(qn).strip())
                kk=kk+1
        c.setFont("Helvetica", 6)
        deltaY=10
        DDy = DDy - deltaY
        lotowners = {}
        for lo in imm.lot_owner_set.filter('is_current_owner =', True).filter('is_linked =', True):
            lotowners[lo.lot.number] = lo.owner    
 #       s.isdigit() #for sorting atoi(s)
        immlot = imm.lot_set.order('number').run()
        immlotS = sorted(immlot, key= attrgetter('number'), cmp = srtLot)
        for lo in immlotS: #bTable body
            DDyStore = DDy
            DDy = DDy - deltaY
#            ttabl = [unicode(lo.number), unicode(lo.lot_type), unicode(lo.immeuble),
#                           unicode(lo.escalier),unicode(lo.etage), unicode(lo.surface), unicode(lo.key().name()),unicode(" "),unicode(" ")]
            lotowner = ''
            if lo.number in lotowners.keys():
                lotowner = lotowners[lo.number]
            ttabl = [lo.number, lo.lot_type, lo.batiment, lo.escalier, lo.etage,
                                                         lo.surface, lotowner]
            kk=0
            for lq in ttabl:
                if kk == 6:
                    if lq:
                        c.drawCentredString( rrow[kk]+5 , DDy-deltaY, unicode( lq ) )
                    else:
                        c.setStrokeColorRGB(1.,0.,0.)
                        c.setFillColorRGB(1.,0.,0.)
                        c.drawCentredString( rrow[kk]+5 , DDy-deltaY, unicode("Assigner un proprietare" ) )
                        c.setStrokeColorRGB(0.,0.,0.)
                        c.setFillColorRGB(0.,0.,0.)
                else : 
                    if kk == 0:
                        c.drawString( 15 , DDy-deltaY, unicode( lq ) )
                    else:  
                        c.drawString( lrow[kk-1]+5 , DDy-deltaY, unicode( lq ) )
                kk=kk+1
            DDyStore2 = DDy
            for lw in lo.lotsckeys.run():
                c.drawString( 383 , DDy-deltaY, unicode(lw.charges_key).strip() )
                c.drawRightString( 550 , DDy-deltaY, unicode(lw.tantieme).strip() )
                DDy = DDy-deltaY
            if DDyStore2 == DDy:
                c.setStrokeColorRGB(1.,0.,0.)
                c.setFillColorRGB(1.,0.,0.)
                c.drawString( 383 , DDy-deltaY, unicode("Selectione un cle") )
                c.drawCentredString( 535 , DDy-deltaY, unicode("Manque tantieme") )
                c.setStrokeColorRGB(0.,0.,0.)
                c.setFillColorRGB(0.,0.,0.)
                DDy = DDy-deltaY
            c.line(10,DDy-deltaY,10,DDyStore)
            for lp in lrow:
                c.line(lp,DDy-deltaY,lp,DDyStore)
            c.line(10, DDy-deltaY, 570, DDy-deltaY)
        c.restoreState()
        c.showPage()
        c.save()

#------------------------------------------------------------------------------------------------------        
    def op_Budget(self, imm_id):#Budget
        
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        imm = immeuble.get_by_id(int(imm_id))  
        ssyn = imm.syndic
        period = period_concept.all().get()
        #imm = immeuble.get_by_id([id immeuble])      
        
        
        
        self.response.headers['Content-Type'] = 'application/pdf'
        self.response.headers['Content-Disposition'] = 'attachment; filename=budget.pdf'
        
        c = canvas.Canvas(self.response.out, pagesize=A4)
        pwidth, pheight = A4
        c.translate(0,pheight-50)
        c.saveState() 
        #
        title = "Balance immeuble"
        title2 = "Avant repartition"
        self.draw_header(imm,ssyn,c,title,title2)

        # Draw a table        
        deltaY = 12.
        DDy = -130
        c.rect(20,DDy-40,560,20, fill=0)
        c.setFont("Helvetica", 8)
        c.setStrokeColorRGB(0.,0.,0.)
        c.setFillColorRGB(0.0,0.0,0.0)
        c.drawString(350, DDy+15,unicode("Arretee au 15/03/2013 : "))
        
        DDy = DDy - 40
        
        rrow = [  50,  120,  180, 330, 490, 550]#
        lrow = [20, 90,  150, 210, 460, 520, 580]#
        rnom = ['Debit', 'Credit', 'Compte', 'Libelle', 'Debit',
                 'Credit']
        
        c.setFont("Helvetica", 10)
        kk = 0
        for qq, qn in map(None,rrow,rnom): # header
                #sw = c.stringWidth( unicode(qn).strip())/2
                c.drawCentredString(qq , DDy+5, unicode(qn).strip())
        for ql in lrow:
            c.line(ql,DDy,ql,DDy+20)

        
        DDy = DDy -deltaY 
        
        s = imm.get_summary_charges_key()
 
        c.setFont("Helvetica", 8)
        for i in s:
            c.drawCentredString(rrow[3], DDy, unicode(i))             
            c.drawCentredString(rrow[0], DDy, unicode(s[i]["sum"]))
            c.drawCentredString(rrow[1], DDy, unicode(s[i]["total"]))              
            #o = i['sum_by_keys'].keys() 
            #o.sort()   # key sorting for output
            #for c_key in o:
            #    c.drawString(250, DDy, unicode(c_key.strip()))
            #    c.drawString(400, DDy, unicode(i['sum_by_keys'][c_key]['charges_key'].th_tantiem_sum).strip())
 
            DDy = DDy - deltaY        
        c.restoreState()
        c.showPage()
        c.save()

#------------------------------------------------------------------------------------------------------        

    def op_AppFond(self, imm_id, frreq_id):
      
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        
        fr_req = fundraising.get_by_id(int(frreq_id))
        period = fr_req.period
        imm = fr_req.immeuble  
        ssyn = imm.syndic

        lots, sum, b_sum = period.get_fundraising_distribution_v2(fr_req.amount)
        #if abs( fr_req.amount-sum ) > 0.001 :        
            ##self.redirect("/ams/immeuble")
            #self.response.write("ERROR! Initial amount = %s. Return sum is  %f, Initial budget is %f " % (fr_req.amount, sum, b_sum ))
            #return
        self.response.headers['Content-Type'] = 'application/pdf'
        self.response.headers['Content-Disposition'] = 'attachment; filename=AppDeFond.pdf'
        
        c = canvas.Canvas(self.response.out, pagesize=A4)
        pwidth, pheight = A4


        lo_codes = {}
        for l in  lots.keys():
            if  lots[l]['lot_owner']:
                keyname = "%s_%s" %  ( lots[l]['lot_owner'].owner, lots[l]['lot_owner'].code)
            else:
                keyname = 'NoOwner'
            if  keyname in lo_codes.keys():
                lo_codes[keyname].append({'lot': lots[l]['lot'], 'lot_owner':lots[l]['lot_owner'], 'charges_keys':lots[l]['charges_keys'],  'budget_lot_sum': lots[l]['budget_lot_sum'],'lot_sum': lots[l]['lot_sum'] })
            else:
                lo_codes[keyname] = [{'lot': lots[l]['lot'], 'lot_owner':lots[l]['lot_owner'], 'charges_keys':lots[l]['charges_keys'], 'budget_lot_sum': lots[l]['budget_lot_sum'],  'lot_sum': lots[l]['lot_sum'] }]



        rrow = [100,  200,  270,  370,  460, 540] #
        lrow = [20, 180,  220, 320,  420,  510, 580]#
        rnom = [ 'Nature de l\'appel', 'Lot', 'Montant a prepartir',
                         'Votre quote-part','Millieme','Tantieme']
        
        
        stored_name = ""
        nnpage = 0
        DDy = -95.
        deltaY = 12.
        mont_qpart = 0.0
        total_appel = 0.0

        for l in  lo_codes:
            for i in lo_codes[l]:
                if stored_name != l:
                    if nnpage != 0:   
                        for lp in lrow:
                            c.line(lp,DDy,lp,DDy+8)   
                        c.line(20, DDy, 580, DDy)
                        DDy = DDy - deltaY
            
                        c.setStrokeColorRGB(0.0,0.0,0.0)
                        c.setFillColorRGB(0.1,0.1,0.1)
            
                        c.rect(lrow[2],DDy-20,360,20, fill=0)
                        DDy = DDy - 20
                        c.line(lrow[2],DDy-deltaY,lrow[2],DDy+20)
                        c.line(lrow[3],DDy-deltaY,lrow[3],DDy+20)
                        c.line(lrow[4],DDy-deltaY,lrow[4],DDy+20)
                        c.line(lrow[6],DDy-deltaY,lrow[6],DDy+20)
                        c.setFont("Helvetica", 10) 
                        c.drawCentredString( rrow[2] , DDy+5, unicode("Total appel ") )
                        c.drawCentredString( rrow[3] , DDy+5, unicode("Total quote-part") )
                        c.drawCentredString( lrow[5] , DDy+5, unicode("Total a payer") )
                        c.setFont("Helvetica", 8) 
                        DDy = DDy - deltaY
                        c.drawCentredString( rrow[2] , DDy+3, unicode("%.2f" % total_appel))
                        c.drawCentredString( rrow[3] , DDy+3, unicode("%.2f" % mont_qpart))
                        c.drawCentredString( lrow[5], DDy+3, unicode("%.2f" % mont_qpart))
                        c.line(lrow[2], DDy, lrow[6], DDy)

                        DDy = -pheight + 100
                        c.rect(40,DDy,lrow[1]-20,40, fill=0)
            
                        c.drawCentredString( rrow[0] , DDy+31, unicode("Observation :") )
                        c.drawCentredString( rrow[0] , DDy+3, unicode(fr_req.remarks) )

                        c.restoreState()
                        c.showPage()
                    
                        DDy = -95.
                        deltaY = 12.
                        mont_qpart = 0.0
                        total_appel = 0.0


                    nnpage = nnpage + 1
                 
                    stored_name = l
                    c.translate(0,pheight-50)
                    c.saveState() 

                    title = "Appel de fonds"
                    self.draw_header(imm,ssyn,c,title)

                    c.setFont("Helvetica", 6)
                    c.drawString(310, DDy,"Destinaire : ")
                    c.setFont("Helvetica", 8)
                    DDy = DDy - deltaY
               
                    if l != 'NoOwner':
                        c.drawString(320, DDy,unicode("%s" % (i['lot_owner'].owner)))
                        c.drawString(320, DDy-9,unicode(i['lot_owner'].owner.address))
                    else:
                        c.drawString(320, DDy,unicode("'No owner!!!!'"))
                        c.drawString(320, DDy-9,unicode( 'Total for lot: %f' % i['lot_sum']))
                        c.drawString(320, DDy-16,unicode('Total for lot (budget): %f' % i['budget_lot_sum']))
                    #continue
 
                    DDy = -160
                # Draw a table
                    c.setStrokeColorRGB(0.0,0.0,0.0)
                    c.setFillColorRGB(0.1,0.1,0.1)
                    c.rect(20,DDy-20,560,20, fill=0)
            
                    c.setFont("Helvetica", 10)
                    c.setStrokeColorRGB(0.,0.,0.)
                    c.setFillColorRGB(0,0,0)


                    for lp in lrow:
                        c.line(lp,DDy,lp,DDy-20)
            
                    DDy = DDy-15
                    for qq, qn in map(None,rrow,rnom): # header
                        c.drawCentredString(qq , DDy+3, unicode(qn),mode=0)
                
            
                    DDy = DDy-30
                    c.setFont("Helvetica", 6)  
                    c.drawCentredString( rrow[0] , DDy+17, unicode("Budget du %s" % period) )
                    c.drawCentredString( rrow[0] , DDy+10, unicode(fr_req.desc) )
                    for lp in lrow:
                        c.line(lp,DDy-5,lp,DDy+30)
            
                    c.setFont("Helvetica", 8) 
                    DDy = DDy-5

                ck_o = i['charges_keys'].keys()
                ck_o.sort()

                for k in ck_o:
                    for lp in lrow:
                        c.line(lp,DDy-5,lp,DDy+deltaY)
                    c.setFont("Helvetica", 8) 
                    c.drawString(lrow[0] +10, DDy,       unicode(i['charges_keys'][k]['charges_key']))
                    c.drawCentredString(lrow[1]+15, DDy, unicode(i['lot'].number))
                    #c.drawRightString(lrow[2]-10, DDy,   unicode("%.2f" % i['charges_keys'][k]['budget_ck_amount']))
                    #c.drawRightString(lrow[3]-10, DDy,   unicode("%.2f" % i['charges_keys'][k]['ck_amount']))
                    c.drawRightString(lrow[4]-10, DDy,   unicode("%.2f" % i['charges_keys'][k]['tantieme']))
                    c.drawRightString(lrow[5]-10, DDy,   unicode("%.2f" % i['charges_keys'][k]['sum']))
                    
                    exp_ordered = i['charges_keys'][k]['expenditures'].keys()
                    exp_ordered.sort()
                    DDy = DDy - deltaY
                    for e in exp_ordered:
                        c.setFont("Helvetica", 6)  
                        c.drawString(lrow[0] +15, DDy, unicode(i['charges_keys'][k]['expenditures'][e]['expenditure'].title))
                        c.drawRightString(lrow[4]-10, DDy, unicode("%.2f" % i['charges_keys'][k]['expenditures'][e]['amount']))

                        mont_qpart +=  i['charges_keys'][k]['expenditures'][e]['amount']
                        #total_appel += i['charges_keys'][k]['ck_amount']
                        for lp in lrow:
                            if lp not in [180,  220]:
                                c.line(lp,DDy-2,lp,DDy+deltaY)
                        DDy = DDy - deltaY
                    # DDy = DDy - deltaY
            # 
        for lp in lrow:
            c.line(lp,DDy,lp,DDy+8)   
        c.line(20, DDy, 580, DDy)
        DDy = DDy - deltaY
            
        c.setStrokeColorRGB(0.0,0.0,0.0)
        c.setFillColorRGB(0.1,0.1,0.1)
            
        c.rect(lrow[2],DDy-20,360,20, fill=0)
        DDy = DDy - 20
        c.line(lrow[2],DDy-deltaY,lrow[2],DDy+20)
        c.line(lrow[3],DDy-deltaY,lrow[3],DDy+20)
        c.line(lrow[4],DDy-deltaY,lrow[4],DDy+20)
        c.line(lrow[6],DDy-deltaY,lrow[6],DDy+20)
        c.setFont("Helvetica", 10) 
        c.drawCentredString( rrow[2] , DDy+5, unicode("Total appel ") )
        c.drawCentredString( rrow[3] , DDy+5, unicode("Total quote-part") )
        c.drawCentredString( lrow[5] , DDy+5, unicode("Total a payer") )
        c.setFont("Helvetica", 8) 
        DDy = DDy - deltaY
        c.drawCentredString( rrow[2] , DDy+3, unicode("%.2f" % total_appel))
        c.drawCentredString( rrow[3] , DDy+3, unicode("%.2f" % mont_qpart))
        c.drawCentredString( lrow[5], DDy+3, unicode("%.2f" % mont_qpart))
        c.line(lrow[2], DDy, lrow[6], DDy)

        DDy = -pheight + 100
        c.rect(40,DDy,lrow[1]-20,40, fill=0)
            
        c.drawCentredString( rrow[0] , DDy+31, unicode("Observation :") )
        c.drawCentredString( rrow[0] , DDy+3, unicode(fr_req.remarks) )

        c.restoreState()
        c.showPage()
        c.save()

    def op_list(self, imm_id):
      
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(users.create_login_url(self.request.uri))
            return

        h = i18n.gettext("Reports")
        title = i18n.gettext("Real estate management application")
        header = i18n.gettext("ATENET. Reports")
        imm = immeuble.get_by_id(int(imm_id)) 
        template_values = {
                'title': title,
                'header': header,
                'content_header': h,
                'main_content': i18n.gettext('Reports for: %s' % imm),
                "immeuble": imm,
                'app_user': au,
                'section': 'reports',
                'lurl': users.create_logout_url('/')
            }
        
#        self.render_template('templates/main_page.html', name=self.request.get('name'))
        template = self.jinja2.get_template('templates/report_page.html')
        self.response.out.write(template.render(template_values))



        #lo_l = []
        #for lot in imm.lot_set.run():
        #    for lo in lot.owner_lots.run():
        #        lo_l.append(lo.owner)
        #
        #lo_l = functions.distinct(lo_l)
        ################################
                
        #lotowners = {}
        #lotownersF = []
        #for lo in imm.lot_owner_set.filter('is_current_owner =', True).filter('is_linked =', True):
        #        lotowners[lo.lot.number] = lo.owner
        #        lotownersF[lo.lot.number] = lo  
      
        #for lo in imm.lot_set.order('number').run(): #bTable body
        #    lotowner = ''
        #    if lo.number in lotowners.keys():
        #        lotowner = lotowners[lo.number]
                
        #ttabl = [lo.number, lo.lot_type, lo.batiment, lo.escalier, lo.etage,
        #                                                 lo.surface, lotowner]
                
 #           rrow = [70, 200,  300, 340, 400, 470] #
 #           lrow = [20, 250,  350, 390, 435, 500, 540 ,580]#
 #           rnom = ['Identification du coproprietaire', 'Base de repartition', 'Cle', 
 #                       'Tant.', 'Val.Tant','Montant']
#            for qq, qn in map(None,rrow,rnom): # header
 #               c.drawString(qq , DDy+5, unicode(qn),mode=0)
 #               if qq != 35:
#                   c.line(qq-5, DDy-20, qq-5, DDy+20)
#def AddDocx(docxfile, document,coreprops,appprops,contenttypes,websettings,wordrelationships):
#    '''Save a modified document'''
#    assert os.path.isdir(template_dir)
#   
#    # Move to the template data path
#    #prev_dir = os.path.abspath('.') # save previous working dir
#
#    # Serialize our trees into out zip file
#    treesandfiles = {document:'word/document.xml',
#                     coreprops:'docProps/core.xml',
#                     appprops:'docProps/app.xml',
#                     contenttypes:'[Content_Types].xml',
#                     websettings:'word/webSettings.xml',
#                     wordrelationships:'word/_rels/document.xml.rels'}
#    for tree in treesandfiles:
#        log.info('Saving: '+treesandfiles[tree] )
#        treestring = etree.tostring(tree, pretty_print=True)
#        docxfile.writestr(treesandfiles[tree],treestring)
#
#    # Add & compress support files
#    files_to_ignore = ['.DS_Store'] # nuisance from some os's
#    docxfile.write('C:\\Users\\\Ilia.Arnaoutov\\\workspace\\apnet\\docx\\template\\DocProps\\thumbnail.jpeg','DocProps\\thumbnail.jpeg')
#    docxfile.write('C:\\Users\\\Ilia.Arnaoutov\\\workspace\\apnet\\docx\\template\\word\\styles.xml','word\\styles.xml')
#    docxfile.write('C:\\Users\\\Ilia.Arnaoutov\\\workspace\\apnet\\docx\\template\\word\\settings.xml', 'word\\settings.xml')
#    docxfile.write('C:\\Users\\\Ilia.Arnaoutov\\\workspace\\apnet\\docx\\template\\word\\numbering.xml', 'word\\numbering.xml')
#    docxfile.write('C:\\Users\\\Ilia.Arnaoutov\\\workspace\\apnet\\docx\\template\\word\\fontTable.xml', 'word\\fontTable.xml')
#    docxfile.write('C:\\Users\\\Ilia.Arnaoutov\\\workspace\\apnet\\docx\\template\\word\\media\\image1.png', 'word\\media\\image1.png')
#    docxfile.write('C:\\Users\\\Ilia.Arnaoutov\\\workspace\\apnet\\docx\\template\\word\\theme\\theme1.xml', 'word\\theme\\theme1.xml')
#    docxfile.write('C:\\Users\\\Ilia.Arnaoutov\\\workspace\\apnet\\docx\\template\\_rels\\.rels', '_rels\\.rels')
#  Serialize our trees into out zip file
#    treesandfiles = {document:'word/document.xml',
#                     coreprops:'docProps/core.xml',
#                     appprops:'docProps/app.xml',
#                     contenttypes:'[Content_Types].xml',
#                     websettings:'word/webSettings.xml',
#                     wordrelationships:'word/_rels/document.xml.rels'}
#
#    # Add & compress support files
#    #files_to_ignore = ['.DS_Store'] # nuisance from some os's
#    for dirpath,dirnames,filenames in os.walk('.'):
#        for filename in filenames:
#            if filename in files_to_ignore:
#                continue
#            templatefile = join(dirpath,filename)
#            archivename = templatefile[2:]
#            #log.info('Saving: %s', archivename)
#            docxfile.write(templatefile, archivename)

#    docxfile.close()
#    return

#def CreateDocx( zipstream):
    
    
        # Create our properties, contenttypes, and other support files
        #coreprops = coreproperties(title='Python docx demo',subject='Making docx from Python',creator='APNET',keywords=['python','Office Open XML','Word'])
        #appprops = appproperties()
        #cotypes = contenttypes()
       # websets = websettings()
       # wordrels = wordrelationships(relationships)
        
        # Save our document
        #savedocx(document,coreprops,appprops,cotypes,websets,wordrels,'F:\Testdocx.docx')    
        
        #self.response.headers['Content-Type'] ='application/zip'
        #self.response.headers['Content-Disposition'] = \
        #    'attachment; filename="outfile.zip"'    

        # compress files and emit them directly to HTTP response stream
        #with closing(ZipFile(self.response.out, "w", ZIP_DEFLATED)) as outfile:
        #     Create Docx as zipfile
        #     AddDocx(outfile, document,coreprops,appprops,cotypes,websets,wordrels)
         #zipstream=StringIO.StringIO()
        #outfile = zipfile.ZipFile(file=zipstream,compression=zipfile.ZIP_DEFLATED,mode="w")
        #AddDocx(outfile, document,coreprops,appprops,cotypes,websets,wordrels)
        #outfile.writestr("data.txt.zip",text.encode("utf-8"))
        #outfile.close()
        #zipstream.seek(0)
        #return

#
#        lo_l = []
#        for lot in imm.lot_set.run():
#            for lo in lot.owner_lots.run():
#                lo_l.append(lo.owner)
#        
#        lo_l = functions.distinct(lo_l)
#        relationships = relationshiplist()
#
#    # Make a new document tree - this is the main part of a Word document
#        document = newdocument()
#    
#    # This xpath location is where most interesting content lives 
#        docbody = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]
#    
#    # Append two headings and a paragraph
#        docbody.append(heading('Syndic:',0))
#        docbody.append(paragraph(unicode(ssyn.adress)))  
#        if ssyn.additional_adress:
#            docbody.append(paragraph(unicode(ssyn.additional_adress)))
#        docbody.append(paragraph(unicode(ssyn.postalcode) + unicode(' ') + unicode(ssyn.ville)))
#        docbody.append(paragraph("Phone: ",unicode(ssyn.phone)))
#        docbody.append(paragraph("Fax  : ",unicode(ssyn.fax)))
#        docbody.append(paragraph("emal : ",unicode(ssyn.email)))
#        
#        docbody.append(heading('Copropriete : ' + unicode(imm.name),0))
#        docbody.append(paragraph(unicode(imm.adress)))
#        docbody.append(paragraph(unicode(imm.additional_adress)))
#        #docbody.append(paragraph(unicode(imm.postalcode) +" "+ unicode(imm.ville)))
#
#  
#        
#        # Add a numbered list
#       # for ll in lo_l:
#       #     docbody.append(paragraph(str(ll) ,style='ListBullet'))#'ListNumber'.first_name+" "+ll.last_name
#        
#        
#
#        docbody.append(paragraph('Tables are just lists of lists, like this:'))
#        # Append a table
#        ttabl = []
#        rrow = ['Lot', 'type', 'batiment', 'escalier', 'etage', 'surface', 'Proprietaire','Cle de repartition']#,'millieme']
#        ttabl.append(rrow) 
#        for lo in imm.lot_set.run():
#            arr = []
#            for lw in lo.lotsckeys.run():
#                arr.append((unicode("%s - %s" % (lw.charges_key, lw.tantieme)),"")) 
#            ttabl.append([unicode(lo.number), unicode(lo.lot_type), unicode(lo.immeuble),
#                           unicode(lo.escalier),unicode(lo.etage), unicode(lo.surface), unicode(lo.key().name()),paragraph(arr)])
#        docbody.append(table(ttabl))
##        docbody.append(table([['A1','A2','A3'],['B1','B2','B3'],['C1','C2','C3']]))
#
# 
#        # Add a pagebreak
#        docbody.append(pagebreak(type='page', orient='portrait'))
#
#        docbody.append(heading('Next Page',2))
#        docbody.append(paragraph('''ATNET'''))
#        
#        
#        coreprops = coreproperties(title='APNET Document',subject='Lots List',creator='APNET',keywords=['python','Office Open XML','Word'])
#        appprops = appproperties()
#        cotypes = contenttypes()
#        websets = websettings()
#        wordrels = wordrelationships(relationships)
#        # file creation
#        zipstream=StringIO.StringIO()
#        outfile = zipfile.ZipFile(file=zipstream,compression=zipfile.ZIP_DEFLATED,mode="w")
#        AddDocx(outfile, document,coreprops,appprops,cotypes,websets,wordrels)
#        zipstream.seek(0)
# 
#        #self.response.headers['Content-Type'] = 'application/zip'
#        #self.response.headers['Content-Type'] = 'multipart/x-zip'
#        self.response.headers['Content-Disposition'] = 'attachment; filename="LotsList.docx"'
#        self.response.out.write(zipstream.getvalue())

#textobject = c.beginText()
#textobject.setTextOrigin(35, 25)
#textobject.setFont("Helvetica-Oblique", 14)
#leading = 8
#for line in lyrics:
#textobject.setLeading(leading)
#textobject.textLine("%s: %s" %(leading,line))
#leading = leading+2.5
#textobject.setFillColorCMYK(0.8,0,0,0.3)
#textobject.textLines('''  ''')
#c.drawText(textobject)

